package com.brokendust.client.api.util.image;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.util.ResourceLocation;

import java.io.InputStream;
import java.net.URL;

public class ImageInfo {
    public boolean web;
    NativeImage nativeImage;
    DynamicTexture dynamicTexture;
    ResourceLocation resourceLocation;
    String path;
    int width;
    int height;

    public ImageInfo(String path) {
        this.path = path;
        if (path.startsWith("http")) {
            this.web = true;
            this.setUrl(path);
        } else {
            this.web = false;
            this.setPath(path);
        }
    }

    public void setUrl(String urlIn) {
        try {
            URL url = new URL(urlIn);
            InputStream is = url.openStream();
            this.nativeImage = NativeImage.read(is);
            this.width = this.nativeImage.getWidth();
            this.height = this.nativeImage.getHeight();
            this.dynamicTexture = new DynamicTexture(this.nativeImage);
        } catch (Exception ex) {
        }
    }

    public void setPath(String path) {
        this.resourceLocation = new ResourceLocation(path);
        try {
            InputStream is = Minecraft.getInstance().getResourceManager().getResource(this.resourceLocation).getInputStream();
            this.nativeImage = NativeImage.read(is);
            this.width = this.nativeImage.getWidth();
            this.height = this.nativeImage.getHeight();
        } catch (Exception ex) {
        }
    }

    public ResourceLocation getResourceLocation() {
        if (this.web) {
            try {
                return Minecraft.getInstance().getTextureManager().register("menu", this.dynamicTexture);
            } catch (NullPointerException exception) {
                return new ResourceLocation("textures/gui/demo_background.png");
            }
        }
        return this.resourceLocation;
    }

    public int getWidth() {
        return this.width;
    }

    public int getHeight() {
        return this.height;
    }
}
